<template>
	<div id="write">
		<el-header>
			<div style="display: flex;justify-content: space-between;align-items: center;height:100%;">
				<div style="display: flex;justify-content: space-around;align-items: center;">
					<div class="leaf"></div>
					<div>
						<div class="me-write-info" v-if="articleForm.title != ''">{{ articleForm.title }}</div>
						<div class="me-write-info" v-else>无标题</div>
						<div class="username">{{ user.username }}&emsp;/&emsp;
							<span v-if="stores.filter(item => item.id === Number(articleParam.storeid))[0]">{{
								stores.filter(item => item.id
									=== Number(articleParam.storeid))[0].storename
							}}区</span>
						</div>
					</div>
				</div>
				<div class="me-write-btn">
					<el-button @click="publishShow()" size="small" type="success">发布</el-button>
					<el-button @click="cancel" size="small">取消 </el-button>
				</div>
			</div>
		</el-header>
		<el-container>
			<el-container class="me-area me-write-box">
				<el-main class="me-write-main">
					<div class="me-write-title">
						<input v-model="articleForm.title" placeholder="请输入标题" class="me-write-input">
					</div>
					<div id="placeholder" style="visibility: hidden;height: 89px;display: none;"></div>
					<mavon-editor class="me-editor" ref="md" v-model="editor.value" @imgAdd="imgAdd" :ishljs="true"
						previewBackground="#ffffff" boxShadowStyle="none" placeholder="在这输入正文" v-bind="editor">
					</mavon-editor>
					<el-form style="border-top:1px solid rgb(230, 230, 230,0.7);padding:20px 10px">
						<el-form-item label="知识库：">
							<el-select v-model="articleParam.storeid" placeholder="请选择知识库" size="medium">
								<el-option v-for="s in stores" :key="s.id" :label="s.storename" :value="s.id" disabled>
								</el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="文档权限：">
							<el-radio-group v-model="articleForm.isprivate">
								<el-radio :label="1">私密</el-radio>
								<el-radio :label="0">公开</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-form>
				</el-main>
			</el-container>

			<el-dialog title="附件 权限" :visible.sync="publishVisible" :close-on-click-modal=false
				custom-class="me-dialog">
				<el-form>
					<el-form-item label="附件">
						<input type="file" @change="changeFile" id="fileToUpload">
						<div>
							<el-button size="small" @click="clickBt" type="primary" plain>点击上传附件</el-button>
							<span style="font-size:13px">{{
								articleForm.annexname ? articleForm.annexname :
									'未选择附件文件'
							}}</span>
						</div>
					</el-form-item>
					<el-form-item label="附件权限">
						<el-select v-model="articleForm.auth" placeholder="请选择附件权限" size="small">
							<el-option v-for="a in authOptions" :key="a.value" :label="a.label" :value="a.value">
							</el-option>
						</el-select>
					</el-form-item>
				</el-form>

				<div slot="footer" class="dialog-footer">
					<el-button @click="publishVisible = false" size="small">取 消</el-button>
					<el-button @click="publish('articleForm')" size="small">发布</el-button>
				</div>
			</el-dialog>
		</el-container>
	</div>
</template>
<script>
import {
	publisharticle,
	getonearticle,
	editarticle,
	upload,
	uploadFile
} from '../api/api.js'
import {
	getallcategory
} from '../api/api.js'
import {
	mavonEditor
} from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'
export default {
	name: 'write',
	created() {
		this.getCategorys();
		if (this.$route.params.id) {
			this.getArticleById(this.$route.params.id);
			this.type = 'update'
		}
		this.$set(this.editor, 'ref', this.$refs.md)
		window.addEventListener('scroll', this.editorToolBarToFixedWrapper, false);
	},
	beforeDestroy() {
		window.removeEventListener('scroll', this.editorToolBarToFixedWrapper, false)
	},
	data() {
		return {
			file: '',
			user: JSON.parse(window.sessionStorage.getItem('user')),
			type: 'add',
			publishVisible: false,
			stores: [],
			pubtype: 'pub',
			articleForm: {
				title: '',
				content: '',
				annexid: '',
				annexname: '',
				annextype:'',
				isprivate: 1,
				auth: 1,
			},
			articleParam: {
				storeid: Number(this.$route.params.storeid),
				parentid: Number(this.$route.params.parentid),
			},
			editor: {
				value: '',
				id: '',
			},
			authOptions: [
				{
					label: '仅自己可下载',
					value: 1
				},
				{
					label: '仅库主和自己可下载',
					value: 2
				},
				{
					label: '公开',
					value: 0
				}
			],
		}
	},
	computed: {
		title() {
			return '写文章 - LULU 乐享'
		}
	},
	methods: {
		clickBt() {
			document.getElementById('fileToUpload').click()
		},
		changeFile(e) {
			//   获取文件
			this.file = e.target.files[0];
			this.getBase64(this.file).then(res => {
				var files = res;
				let data = {
					file: files,
					name: this.file.name,
					type: this.file.name.split('.')[this.file.name.split('.').length - 1],
				}
				uploadFile(data).then(res => {
					if (res.data.status == -1) {
						return this.$message.error('token过期');
					} else {
						this.$message.success('上传成功');
						this.articleForm.annexname = this.file.name;
						this.articleForm.annexid = res.data.data.id;
						this.articleForm.annextype = res.data.data.type;
					}

				})
			})

		},
		imgAdd(pos, $file) {
			console.log($file);
			let that = this
			const imgType = ['image/jpeg', 'image/png'];
			const isLt2M = $file.size / 1024 / 1024 < 2;
			if (!imgType.includes($file.type)) {
				this.$message.error('上传图片仅支持JPG、PNG格式!');
				that.$refs.md.$img2Url(pos, ' ');
			} else if (!isLt2M) {
				this.$message.error('注意上传图片大小不能超过2MB!');
				that.$refs.md.$img2Url(pos, ' ');
			} else {
				upload({ ...$file, imgType: $file.type.split('/')[1] }).then(resp => {
					// 第二步.将返回的url替换到文本原位置![...](./0) -> ![...](url)
					if (resp.data.status == 200) {
						that.$refs.md.$img2Url(pos, `http://${resp.data.imageUrl}`);
					} else {
						that.$message({
							message: `${resp.data.msg}`,
							type: 'error',
							showClose: true
						})
					}

				}).catch(err => {
					that.$message({
						message: err,
						type: 'error',
						showClose: true
					});
				})

			}
		},
		// 二进制流转换为base64 格式。
		getBase64(data) {
			return new Promise((resolve, reject) => {
				const blob = new Blob([data], {
					type: data.type
				}); //类型一定要写！！！
				const reader = new FileReader();
				reader.readAsDataURL(blob);
				reader.onload = () => resolve(reader.result);
				reader.onerror = (error) => reject(error);
			});
		},
		getArticleById(id) {
			getonearticle(id).then(resp => {
				this.articleForm = {
					id: resp.data.data[0].id,
					title: resp.data.data[0].title,
					content: resp.data.data[0].content,
					annexid: resp.data.data[0].annexid,
					annexname: resp.data.data[0].annexname,
					isprivate: resp.data.data[0].isprivate,
					auth: resp.data.data[0].auth,
					author: resp.data.data[0].author
				};
				this.editor.value = resp.data.data[0].content.replace(/\\r\\n/g, "\n").replace(
					/&lt;/g, "<").replace(/&gt;/g, ">")
				if (this.user.id != this.articleForm.author.id) {
					this.$message.error('您没有权限');
					this.$router.replace('/Home');
				}
			}).catch(() => {
				this.$message({
					type: 'error',
					message: '文章加载失败',
					showClose: true
				})
			})
		},
		publishShow() {
			if (!this.articleForm.title) {
				this.$message({
					message: '标题不能为空哦',
					type: 'warning',
					showClose: true
				})
				return
			}

			if (this.articleForm.title.length > 30) {
				this.$message({
					message: '标题不能大于30个字符',
					type: 'warning',
					showClose: true
				})
				return
			}

			if (this.editor.value.length < 1) {
				this.$message({
					message: '内容不能为空哦',
					type: 'warning',
					showClose: true
				})
				return
			}
			this.publishVisible = true;
		},
		publish() {
			let that = this
			this.articleForm.content = this.editor.value.replace(/</g, "&lt;").replace(/>/g,
				"&gt;");
			this.publishVisible = false;
			let loading = this.$loading({
				lock: true,
				text: '发布中，请稍后...'
			})
			if (this.type == 'add') {
				publisharticle(this.articleForm, this.articleParam).then((resp) => {
					if (resp.data.code == 200) {
						loading.close();
						that.$message({
							message: '发布成功啦',
							type: 'success',
							showClose: true
						})
						setTimeout(() => {
							that.$router.push({
								path: `/article/${resp.data.id}`
							})
						}, 500)

					} else {
						that.$message({
							type: 'error',
							message: resp.data.message,
							showClose: true
						});
						loading.close();
					}

				}).catch((error) => {
					loading.close();
					that.$message({
						message: error,
						type: 'error',
						showClose: true
					});
				})
			} else {
				//更新接口
				editarticle(this.articleForm, this.articleParam).then((resp) => {
					if (resp.data.code == 200) {
						that.$message({
							message: '发布成功啦',
							type: 'success',
							showClose: true
						})
						that.$router.push({
							path: `/article/${this.articleForm.id}`
						})
					} else {
						that.$message({
							type: 'error',
							message: '发布文章失败:' + resp.data.message,
							showClose: true
						});
					}
					loading.close();

				}).catch((error) => {
					loading.close();
					that.$message({
						message: error,
						type: 'error',
						showClose: true
					});
				})

			}
		},
		cancel() {
			this.$confirm('文章将不会保存, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				this.$router.go(-1);
			}).catch(() => {
				this.$message({
					type: 'info',
					message: '已取消'
				})
			});
		},
		getCategorys() {
			getallcategory().then(resp => {
				if (resp.data.code == 200) {
					this.stores = resp.data.data;
				} else {
					this.$message({
						type: 'error',
						message: '知识库加载失败',
						showClose: true
					})
				}

			}).catch(error => {
				if (error !== 'error') {
					this.$message({
						type: 'error',
						message: '知识库加载失败',
						showClose: true
					})
				}
			})
		},
		fileChoose(e) {
			console.log(e.target.files);
		},
		editorToolBarToFixed() {

			let toolbar = document.querySelector('.v-note-op');
			let curHeight = document.documentElement.scrollTop || document.body.scrollTop;
			if (curHeight >= 160) {
				document.getElementById("placeholder").style.display = "block"; //bad  用计算属性较好
				toolbar.classList.add("me-write-toolbar-fixed");
			} else {
				document.getElementById("placeholder").style.display = "none";
				toolbar.classList.remove("me-write-toolbar-fixed");
			}
		}
	},
	components: {
		mavonEditor
	},
}
</script>

<style scoped="scoped">
body {
	font-size: 15px;
}

#fileToUpload {
	display: none;
}

.el-button {
	margin: 8px;
}


::v-deep .v-note-wrapper .v-note-panel .v-note-edit.divarea-wrapper .content-input-wrapper {
	overflow: initial;
	word-break:break-all !important;
}

::v-deep .v-note-wrapper .v-note-panel .v-note-edit.divarea-wrapper.transition {
	overflow: initial;
}

::v-deep .v-note-wrapper .v-note-panel .v-note-show .v-show-content,
.v-note-wrapper .v-note-panel .v-note-show .v-show-content-html {
	overflow: initial;
}

::v-deep .v-note-wrapper .v-note-panel .v-note-show {
	overflow: initial;
}

#write {
	max-height: 100%;
}

.el-header {
	position: fixed;
	z-index: 1024;
	min-width: 100%;
	box-shadow: 0 2px 3px hsla(0, 0%, 7%, .1), 0 0 0 1px hsla(0, 0%, 7%, .1);
	background-color: #fff;
	height: 30px;
}

.me-write-info {
	font-size: 14px;
	font-weight: 600;
	margin-bottom: 5px;
}

.username {
	font-size: 12px;
	color: #767676;
	text-align: left;

}

.me-write-btn {
	margin-top: 10px;
	display: flex;
}

.me-write-box {
	background-color: #fff;
	min-width: 100%;
	margin: 80px auto 0;
	margin-top: 60px;
	opacity: 0.95;
	justify-content: center;
}

.me-write-main {
	padding: 10px;
	border-radius: 30px;
	max-width: 1300px;
	margin-left: 40px;
	margin-right: 40px;
}


.me-write-input {
	border: none;
	height: 60px;
	width: 100%;
	font-size: 30px;
	margin-bottom: 20px;
	color: #161616;
	font-weight: 600;
	outline: none;
}

input::-webkit-input-placeholder {
	color: #bababa;
}

.me-header-left {
	margin-top: 10px;
}

.me-title img {
	max-height: 2.4rem;
	max-width: 100%;
}

.me-write-toolbar-fixed {
	position: fixed;
	width: 700px !important;
	top: 60px;
}

.v-note-op {
	box-shadow: none !important;
}

.auto-textarea-input,
.auto-textarea-block {
	font-size: 18px !important;
}

.leaf {
	width: 30px;
	height: 30px;
	background-color: #60c763;
	border-top-left-radius: 30px;
	border-bottom-right-radius: 30px;
	margin-right: 10px;
}



::v-deep .markdown-body code {
	color: #ef314e;
	background: rgba(231, 174, 175, 0.2);
}

.v-note-wrapper.fullscreen {
	top: 60px !important
}

::v-deep .hljs-regexp {
	color: #5d9eff !important;
}

::v-deep .markdown-body h1,
::v-deep .markdown-body h2,
::v-deep .markdown-body h3,
::v-deep .markdown-body h4,
::v-deep .markdown-body h5,
::v-deep .markdown-body h6 {
	font-weight: 700 !important;
	color: #375595;
	;
}

::v-deep .markdown-body strong {
	font-weight: 700;
}

::v-deep .markdown-body strong {
	color: #0d72b5;
}

::v-deep .markdown-body thead tr {
	background: rgba(76, 181, 155, 0.15) !important;
	color: #418c64;
}

::v-deep .hljs {
	border-radius: 5px;
	padding: 5px;
	background: rgba(31, 31, 31, 1.0);
	width: 100%;
	color: #e4fbff !important;
	display: flex;
	flex-direction: row;
	justify-content: flex-start;
	flex-wrap: wrap;
}

::v-deep .hljs code {
	background: none;
	color: #e4fbff !important;
}

::v-deep .hljs-name {
	color: #ff4e51;
}

::v-deep .markdown-body img {
	max-width: 90%;
	z-index: 9999 !important;
}

::v-deep .hljs-punctuation {
	color: #fff;
}

::v-deep .hljs-number {
	color: #9d6fff;
}

::v-deep .hljs-keyword {
	color: #ff2c64;
}

::v-deep .hljs-operator {
	color: #ff3953;
}

::v-deep .hljs-type {
	color: #f1984e;
}

::v-deep::v-deep .hljs-selector-pseudo {
	color: #f1984e;
}

::v-deep .hljs-subst {
	color: #72ce5d;
}

::v-deep .markdown-body blockquote {
	color: #4a4b56 !important;
	border-left: .25em solid #e38658;
	padding: 10px;
	background: rgba(249, 195, 177, 0.1);
}

::v-deep.markdown-body mark {
	background: rgba(154, 255, 131, 0.4) !important;
}

::v-deep .hljs-variable.language_ {
	color: #ffac38 !important;
}

::v-deep .hljs-attr {
	color: #86e751;
}

::v-deep .hljs-string {
	color: #ffcd7b;
}

::v-deep .hljs-variable {
	color: #c8f572;
}

::v-deep .hljs-comment {
	color: #b8b8b8;
}

::v-deep .hljs-selector-class {
	color: #7feb51;
}

::v-deep .hljs-selector-tag {
	color: #ef7e49;
}

::v-deep .hljs-selector-id {
	color: #7feb51;
}

::v-deep .hljs-doctag {
	color: #ff5a5d;
}

::v-deep .hljs-attribute {
	color: #8fd8ff;
}

::v-deep .hljs-title,
.hljs-title.class_,
.hljs-title.class_.inherited__,
.hljs-title.function_ {
	color: #7deb55 !important;

}

::v-deep .hljs-literal {
	color: #8275fa;
}

::v-deep .hljs-params {
	color: #72fff6;
}

::v-deep .hljs-title class_ {
	color: #38bac6;
}

::v-deep .markdown-body pre {
	border-radius: 10px !important;
	margin: 0;
	padding: 2px;
	width: 100% !important;
	display: flex;
	justify-content: flex-start;
	flex-wrap: wrap;
	flex-direction: row;

}

::v-deep .markdown-body pre code {
	width: 100% !important;

}

::v-deep .markdown-body a {
	color: #3e94df;
	font-weight: 600;
	font-size: 16px !important;

}
</style>
